Setting the Position Type

Description

The position property sets the method by which an element is positioned.

The allowed values are:

  • static - laid out as normal. This is the default value.
  • relative - positioned relative to its normal position.
  • absolute - positioned relative to its first ancestor that has a position value other than static.
  • fixed - positioned relative to the browser window.

You use the top, bottom, left, and right properties to offset the element from the element specified by the position property.

The relative value applies the top, bottom, left, and right properties to position the element relative to where it would be under the static value.

The absolute value positions the element relative to the nearest ancestor that has a position value other than static. If there is no such element, the element is positioned relative to the body element.

When you use the fixed value, the element is placed relative to the browser window. The element occupies the same location, even when the rest of the content is scrolled up or down.

Example

The following code demonstrates the effect of the different values.


<!DOCTYPE HTML>
<html>
<head>
<style>
img {<!--  w  ww  .  ja  v  a  2 s  .co m-->
  top: 5px;
  left: 150px;
  border: medium double black;
}
</style>
</head>
<body>
  <p>This is a test.</p>
  <p>This is a test.</p>
  <img id="myID" src="http://www.java2s.com/style/download.png"/>
  <p>This is a test.</p>
  <p>
    <button>Static</button>
    <button>Relative</button>
    <button>Absolute</button>
    <button>Fixed</button>
  </p>
  <script>
    var buttons = document.getElementsByTagName("BUTTON");
    for (var i = 0; i < buttons.length; i++) {
      buttons[i].onclick = function(e) {
        document.getElementById("myID").style.position = e.target.innerHTML;
      };
    }
  </script>
</body>
</html>

Click to view the demo





















Home »
  HTML CSS »
    CSS »




CSS Introduction
CSS Background
CSS Border
CSS Box Layout
CSS Text
CSS Font
CSS Form
CSS List
CSS Selectors
CSS Others
CSS Table